<!--
* @FileDescription: 语音播报
* @Date: 2022年11月25日 16:53:16
* TODO:
* [] Demo
-->

<template>
	<el-container style="height:100%">
		<el-form
			ref="queryForm"
			:model="queryParams"
			:inline="true"
			label-width="68px"
		>
			<el-form-item label="模板名称" prop="name">
				<el-input
					v-model="queryParams.name"
					placeholder="请输入模板名称"
					clearable
					size="small"
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="应用业务">
				<el-select
					v-model="queryParams.bizinfoName"
					placeholder="请选择应用业务"
					@keyup.enter.native="handleQuery"
					multiple
				>
					<el-option
						v-for="item in deptList"
						:label="item.name"
						:value="item.id"
						@keyup.enter.native="handleQuery"
					>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="状态">
				<el-select
					v-model="queryParams.status"
					placeholder="请选择状态"
					@keyup.enter.native="handleQuery"
				>
					<el-option
						v-for="item in statusOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="创建时间">
				<el-date-picker
					v-model="queryParams.createDate"
					type="date"
					placeholder="选择日期"
					@keyup.enter.native="handleQuery"
          value-format="yyyy-MM-dd"
				>
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					icon="el-icon-search"
					size="mini"
					@click="handleQuery"
					>{{ $t('elButton.search') }}
				</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
					$t('elButton.reset')
				}}</el-button>
			</el-form-item>
		</el-form>
		<div style="padding:10px;">
			<el-button type="primary" @click="add">新增</el-button>
			<el-button type="warning" @click="deleteItem">删除</el-button>
		</div>
		<el-main>
			<el-table
				ref="multipleTable"
				:data="tableData"
				tooltip-effect="dark"
				style="width: 100%"
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55"> </el-table-column>
				<el-table-column prop="name" label="模板名称"> </el-table-column>
				<el-table-column prop="mode" label="播报模式">
					<template slot-scope="scope">
						{{ handleMode(scope.row.voiceBroadcastMode[0].mode) }}
					</template>
				</el-table-column>
				<el-table-column prop="bizinfoName" label="应用业务">
					<template slot-scope="scope">
						{{ handleBizinfoName(scope.row.bizIds) }}
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态">
					<template slot-scope="scope">
						{{ handleStatus(scope.row.status) || '' }}
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间"> </el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope" width="80">
						<el-button type="primary" @click="editorSpeech(scope.row)"
							>修改</el-button
						>
						<el-button type="warning" @click="deleteItem(scope.row)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
		</el-main>
		<el-footer>
			<el-pagination
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="current"
				:page-sizes="[10, 15, 20, 30]"
				:page-size="size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				style="float:right"
			>
			</el-pagination>
		</el-footer>
		<el-dialog
			:title="title"
			:visible.sync="dialogVisible"
			width="30%"
			append-to-body="true"
		>
			<el-form
				ref="form"
				:model="form"
				label-width="100px"
				class="speech-form"
				size="mini"
				:rules="rules"
			>
				<el-form-item label="名称" :inline="true" prop="name">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item label="状态" :inline="true" prop="status">
					<el-select v-model="form.status" placeholder="请选择">
						<el-option
							v-for="item in statusOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="应用业务">
          <SelectAll v-model="form.bizIds" :valueKey="'id'" :labelKey="'name'" :options="deptList"></SelectAll>
				</el-form-item>
				<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
					<el-tab-pane label="叫号模板" name="0">
						<el-form-item label="播放模式">
							<el-select
								v-model="form.voiceBroadcastMode[formIndex].mode"
								placeholder="请选择"
							>
								<el-option
									v-for="item in playModeOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="前奏音">
							<el-upload
								class="upload-demo"
								action="https://localhost:18089/pro/qbs/voiceBroadcast/upload"
								:on-preview="handlePreview"
								:http-request="uploadFile"
							>
								<el-button size="small" type="primary">点击上传</el-button>
							</el-upload>
						</el-form-item>
						<el-form-item label="前奏音路径">
							<el-input
								disabled
								v-model="form.voiceBroadcastMode[formIndex].prelude"
							></el-input>
						</el-form-item>
						<el-form-item label="文本内容">
							<el-input
								v-model="form.voiceBroadcastMode[formIndex].content"
							></el-input>
						</el-form-item>
						<el-form-item label="播报次数">
							<el-input
								v-model="form.voiceBroadcastMode[formIndex].times"
								type="`number"
							></el-input>
						</el-form-item>
						<el-form-item label="数字播报模式">
							<el-select
								v-model="form.voiceBroadcastMode[formIndex].digitBroadcastMode"
								placeholder="请选择"
							>
								<el-option
									v-for="item in digitBroadcastOption"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
							<i
								class="el-icon-question"
								title="举例说明：
                      1.数字序号: 016播报为'零一六'
                      2.数值: 016播报为'十六'
                      "
							></i>
              </el-form-item>
              <el-form-item label="语言选择">
                <el-select
                  v-model="form.voiceBroadcastMode[formIndex].language"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in [{value:0,label:'中文'},{value:1,label:'藏语'}]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-tab-pane>
					<el-tab-pane label="预先叫号模板" name="1">
            <el-form-item label="播放模式">
							<el-select
								v-model="form.voiceBroadcastMode[formIndex].mode"
								placeholder="请选择"
							>
								<el-option
									v-for="item in playModeOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="前奏音">
							<el-upload
								class="upload-demo"
								action="https://localhost:18089/pro/qbs/voiceBroadcast/upload"
								:on-preview="handlePreview"
								:http-request="uploadFile"
							>
								<el-button size="small" type="primary">点击上传</el-button>
							</el-upload>
						</el-form-item>
						<el-form-item label="前奏音路径">
							<el-input
								disabled
								v-model="form.voiceBroadcastMode[formIndex].prelude"
							></el-input>
						</el-form-item>
						<el-form-item label="文本内容">
							<el-input
								v-model="form.voiceBroadcastMode[formIndex].content"
							></el-input>
						</el-form-item>
						<el-form-item label="播报次数">
							<el-input
								v-model="form.voiceBroadcastMode[formIndex].times"
								type="`number"
							></el-input>
						</el-form-item>
						<el-form-item label="数字播报模式">
							<el-select
								v-model="form.voiceBroadcastMode[formIndex].digitBroadcastMode"
								placeholder="请选择"
							>
								<el-option
									v-for="item in digitBroadcastOption"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
							<i
								class="el-icon-question"
								title="举例说明：
                      1.数字序号: 016播报为'零一六'
                      2.数值: 016播报为'十六'
                      "
							></i> 
            </el-form-item>
              <el-form-item label="语言选择">
                <el-select
                  v-model="form.voiceBroadcastMode[formIndex].language"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in [{value:0,label:'中文'},{value:1,label:'藏语'}]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-tab-pane>
          </el-tab-pane>
				</el-tabs>

				<!-- <el-form-item label="播报语速">
					<el-select v-model="form.speed" placeholder="请选择">
						<el-option
							v-for="item in speedOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
				</el-form-item> -->
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submit">确 定</el-button>
				<el-button @click="dialogVisible = false">取 消</el-button>
			</span>
		</el-dialog>
	</el-container>
</template>
<script>
import SelectAll from '@/components/selectAll'
import {
	getVoiceBroadcast,
	deleteVoiceBroadcast,
	editVoiceBroadcast,
	saveVoiceBroadcast,
	voiceUpload,
} from '@/api/qbs/speech'
import { listBizinfo } from '@/api/qbs/bizinfo'
export default {
	name: 'speech',
	components: {SelectAll},
	data() {
		return {
			title: '', // 弹框标题
			total: 0,
			size: 10,
			current: 1,
			dialogVisible: false,
			rules: {},
			tableData: [],
			multipleSelection: [],
			queryParams: {
				bizinfoName: '',
				apply: '',
				time: '',
				status: '',
			},
			form: { voiceBroadcastMode: [{ mode: '' ,type:'31'},{mode:'',type:'116'}] },
			statusOptions: [{ label: '正常', value: 0 }, { label: '停用', value: 1 }],
			applyOptions: [
				{ label: '启用', value: true },
				{ label: '禁用', value: false },
			],
			playModeOptions: [
				{ label: '前奏音', value: 1 },
				{ label: '文本播报', value: 2 },
				{ label: '前奏音+文本播报', value: 3 },
				{ label: '静音', value: 4 },
			],
			speedOptions: [
				{ label: '常速', value: 0 },
				{ label: '低速', value: 1 },
				{ label: '中速', value: 2 },
				{ label: '快速', value: 3 },
			],
			digitBroadcastOption: [], // 语音数字播报模板
			deptList: [],
			rules: {
				name: [
					{ required: true, message: '请输入活动名称', trigger: 'blur' },
					{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
				],
				status: [
					{
						type: 'number',
						required: true,
						message: '请选择状态',
						trigger: 'change',
					},
				],
			},
			formIndex: 0, // 表单索引（0是叫号数据 1是预叫号）
			activeName: 0,
		}
	},
	// computed:{},
	watch:{
    dialogVisible(val){
      if(!val){
        this.getVoiceBroadcast()
      }
    }
  },
	// mounted(){},
	created() {
		this.getVoiceBroadcast()
		this.getListBizinfo()
		this.getDicts('digit_broadcast_mode').then((response) => {
			this.digitBroadcastOption = response.data
		})
	},
	methods: {
		resetForm() {
			this.form = { voiceBroadcastMode: [{ mode: '' ,type:'31'},{mode:'',type:'116'}] }
		},
		// 获取科室列表
		getListBizinfo() {
			listBizinfo({ current: 1, size: 1000 }).then((response) => {
				this.deptList = response.data.map((item) => {
					// item.id = item.id
					return item
				})
			})
		},
		// 获取语音模板
		async getVoiceBroadcast(query) {
			try {
				let params = query && JSON.parse(JSON.stringify(query))
				if (params && Array.isArray(params.bizinfoName)) {
					params.bizinfoName = params.bizinfoName.join(',')
				}
				const { data, total } = await getVoiceBroadcast({
					size: this.size,
					current: this.current,
					...params,
				})
				this.tableData = data
				this.total = total
			} catch (error) {
				console.log(`getVoiceBroadcast`, error)
			}
		},
		// 上传前奏音
		async uploadFile(file) {
			let formData = new FormData()
			formData.append('file', file.file)
			const { data } = await voiceUpload(formData)
      this.$set(this.form.voiceBroadcastMode[this.formIndex],'prelude',data.path)
		},
		// 处理状态显示
		handleStatus(data) {
			let status = ''
			this.statusOptions.forEach((item) => {
				if (item.value == data) {
					status = item.label
				}
			})
			return status
		},
		// 处理应用业务显示
		handleBizinfoName(data) {
			if (!data) return ''
			if (!data.length) return ''
			let title = []
			let idArray =Array.isArray(data)?data:data.split(',')
			idArray.forEach((id) => {
				this.deptList.forEach((item) => {
					if (item.id == id) {
						title.push(item.name)
					}
				})
			})
			return title.join(',')
		},
		// 处理模式的显示
		handleMode(data){
			let mode = ''
			this.playModeOptions.forEach((item) => {
				if (item.value == data) {
					mode = item.label
				}
			})
			return mode
		},
		toggleSelection(rows) {
			if (rows) {
				rows.forEach((row) => {
					this.$refs.multipleTable.toggleRowSelection(row)
				})
			} else {
				this.$refs.multipleTable.clearSelection()
			}
		},
		handleSelectionChange(val) {
			this.multipleSelection = val
		},
		// 修改
		editorSpeech(data) {
			this.title = '修改语音模板'
			this.resetForm()
			this.dialogVisible = true
			this.form = data
			if (this.form.bizIds && !Array.isArray(this.form.bizIds)) {
				this.form.bizIds = this.form.bizIds.split(',')
				this.form.bizIds = this.form.bizIds.map((item) => {
					return parseInt(item)
				})
			}
		},
		// 新增
		add() {
			this.title = '新增语音模板'
			this.resetForm()
			this.dialogVisible = true
		},
		// 提交表单
		async submit() {
			this.$refs['form'].validate(async (valid) => {
				if (valid) {
          this.form.bizIds = this.form.bizIds.join(',')
					// 编辑
					if (this.form.id) {
						try {
							await editVoiceBroadcast(this.form)
							this.$message({
								message: '修改成功',
								type: 'success',
							})
						} catch (error) {
							this.form.bizIds = []
						}
						this.dialogVisible = false
						this.getVoiceBroadcast()
					} else {
						// 新增
						try {
							const data = await saveVoiceBroadcast(this.form)
							this.$message({
								message: '新增成功',
								type: 'success',
							})
							this.dialogVisible = false
							this.getVoiceBroadcast()
						} catch (error) {
              this.form.bizIds = []
							console.log(`saveVoiceBroadcast`, { error: error })
						}
					}
				} else {
					this.$message({ type: 'error', message: '请按要求填写' })
				}
			})
		},
		// 删除
		async deleteItem(data) {
			if (this.multipleSelection.length) {
				// 删除选中的行
				this.$confirm(`您确定要删除该条数据?`, this.$t('tip'), {
					confirmButtonText: this.$t('submitText'),
					cancelButtonText: this.$t('cancelText'),
					type: 'warning',
				}).then(async () => {
					let ids = this.multipleSelection.map((item) => item.id)
					await deleteVoiceBroadcast(ids.join(','))
					this.getVoiceBroadcast()
				})
			} else {
				if (!data) {
					this.$message({ message: '请选择要删除的模板', type: 'warning' })
				} else {
					// 删除data
					this.$confirm(`您确定要删除该条数据?`, this.$t('tip'), {
						confirmButtonText: this.$t('submitText'),
						cancelButtonText: this.$t('cancelText'),
						type: 'warning',
					}).then(async () => {
						await deleteVoiceBroadcast(data.id)
						this.getVoiceBroadcast()
					})
				}
			}
		},
		// 搜索
		handleQuery() {
			this.getVoiceBroadcast(this.queryParams)
		},
		// 重置
		resetQuery() {
			this.queryParams = {
				bizinfoName: '',
				apply: '',
				time: '',
				status: '',
			}
			this.handleQuery()
		},
		// 处理切换叫号与预叫号
		handleClick(data) {
			console.log(`data`, data.name)
      this.formIndex = data.name
		},
		/** ******
		 * 页码操作
		 *  ****** */
		handleSizeChange(size) {
			this.size = size
			this.getVoiceBroadcast()
		},
		handleCurrentChange(size) {
			this.current = size
			this.getVoiceBroadcast()
		},
	},
}
</script>
<style lang="scss" scoped>
.speech-form {
	.el-form-item {
		margin-top: 0;
	}
}
</style>
